package org.qpcr.community.project.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.hswebframework.web.crud.service.GenericReactiveCrudService;
import org.qpcr.community.project.enums.InterpretationOperator;
import org.qpcr.community.project.model.entity.DataAnalysisExperimentalRecordsEntity;
import org.qpcr.community.project.model.entity.DataAnalysisInterpretationConditionEntity;
import org.qpcr.community.project.model.entity.DataGroupEntity;
import org.qpcr.community.project.model.entity.DataGroupTypeEntity;
import org.qpcr.community.project.request.DataAnalysisRequest;
import org.qpcr.community.project.response.DataAnalysisResultResponse;
import org.qpcr.community.project.response.DataGroupTypeDetail;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import org.qpcr.community.project.model.entity.DataGroupExperimentalRecordsRelateEntity;
import org.hswebframework.reactor.excel.CellDataType;
import org.hswebframework.reactor.excel.ExcelHeader;
import org.hswebframework.reactor.excel.ReactorExcel;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.LinkedHashMap;

@Service
@Slf4j
@RequiredArgsConstructor
public class DataGroupTypeService extends GenericReactiveCrudService<DataGroupTypeEntity, String> {
    @Resource
    private DataGroupExperimentalRecordsRelateService dataGroupExperimentalRecordsRelateService;
    @Resource
    private DataAnalysisExperimentalRecordsService dataAnalysisExperimentalRecordsService;
    @Resource
    private DataAnalysisInterpretationConditionService dataAnalysisInterpretationConditionService;

    public Mono<List<DataGroupTypeDetail>> listByGroupId(String groupId) {
        return createQuery()
            .where(DataGroupTypeEntity::getGroupId, groupId)
            .fetch()
            .collectList()
            .flatMap(groupTypeList -> {
                if (groupTypeList.isEmpty()) {
                    return Mono.just(java.util.Collections.<DataGroupTypeDetail>emptyList());
                }

                // 提取所有组别类型ID
                List<String> groupTypeIds = groupTypeList.stream()
                                                         .map(DataGroupTypeEntity::getId)
                                                         .collect(Collectors.toList());

                // 查询关联数据
                return dataGroupExperimentalRecordsRelateService.findRelateDataByGroupTypeIds(groupTypeIds)
                                                                .map(relateDataMap -> {
                                                                    // 转换为DataGroupTypeDetail列表
                                                                    return groupTypeList.stream()
                                                                                        .map(groupType -> {
                                                                                            DataGroupTypeDetail detail = new DataGroupTypeDetail();
                                                                                            BeanUtils.copyProperties(groupType, detail);

                                                                                            // 设置关联数据
                                                                                            List<org.qpcr.community.project.model.entity.DataGroupExperimentalRecordsRelateEntity> relateDatas =
                                                                                                relateDataMap.getOrDefault(groupType.getId(), java.util.Collections.emptyList());
                                                                                            detail.setRelateDatas(relateDatas);

                                                                                            return detail;
                                                                                        })
                                                                                        .collect(Collectors.toList());
                                                                });
            });
    }

    public Mono<DataGroupTypeDetail> detail(String id) {
        return createQuery()
            .where(DataGroupTypeEntity::getId, id)
            .fetch()
            .single()
            .flatMap(groupType -> {
                DataGroupTypeDetail detail = new DataGroupTypeDetail();
                BeanUtils.copyProperties(groupType, detail);
                // 查询关联数据
                return dataGroupExperimentalRecordsRelateService.findRelateDataByGroupTypeId(id)
                                                                .map(relateDatas -> {
                                                                    detail.setRelateDatas(relateDatas);
                                                                    return detail;
                                                                });
            });
    }


    public DataAnalysisResultResponse analysisSync(DataAnalysisRequest dataAnalysisRequest) {
        return analysis(dataAnalysisRequest).block();
    }


    public Mono<DataAnalysisResultResponse> analysis(DataAnalysisRequest dataAnalysisRequest) {
        // 随机3-5秒的延迟
        try {
            Thread.sleep((long) (Math.random() * 2000 + 3000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String groupId = dataAnalysisRequest.getGroupId();
        List<String> groupTypeIds = dataAnalysisRequest.getGroupTypeIds();

        // 1. 如果传入的groupTypeIds包含other-data，查询未绑定的实验记录
        Mono<List<DataAnalysisExperimentalRecordsEntity>> unBindDataMono = Mono.just(java.util.Collections.<DataAnalysisExperimentalRecordsEntity>emptyList());
        if (groupTypeIds.contains("other-data")) {
            unBindDataMono = dataGroupExperimentalRecordsRelateService.findAllBindRecordIds(groupId)
                .flatMap(recordIds -> dataAnalysisExperimentalRecordsService.listUnBindData(groupId, recordIds));
        }

        // 2. 根据传入的groupTypeIds查询实验记录
        Mono<List<DataAnalysisExperimentalRecordsEntity>> bindDataMono = Mono.just(java.util.Collections.<DataAnalysisExperimentalRecordsEntity>emptyList());
        List<String> validGroupTypeIds = groupTypeIds.stream()
            .filter(id -> !"other-data".equals(id))
            .collect(Collectors.toList());

        if (!validGroupTypeIds.isEmpty()) {
            bindDataMono = dataGroupExperimentalRecordsRelateService.listByGroupIds(validGroupTypeIds)
                .flatMap(relateEntities -> {
                    if (relateEntities.isEmpty()) {
                        return Mono.just(java.util.Collections.<DataAnalysisExperimentalRecordsEntity>emptyList());
                    }
                    List<String> recordIds = relateEntities.stream()
                        .map(DataGroupExperimentalRecordsRelateEntity::getRecordId)
                        .collect(Collectors.toList());
                    return dataAnalysisExperimentalRecordsService.listByIds(recordIds);
                });
        }

        // 3. 合并1、2的结果
        return Mono.zip(unBindDataMono, bindDataMono)
            .flatMap(tuple -> {
                List<DataAnalysisExperimentalRecordsEntity> unBindData = tuple.getT1();
                List<DataAnalysisExperimentalRecordsEntity> bindData = tuple.getT2();

                // 修正allData类型声明，避免类型擦除
                List<DataAnalysisExperimentalRecordsEntity> allData = new ArrayList<DataAnalysisExperimentalRecordsEntity>();
                allData.addAll(unBindData);
                allData.addAll(bindData);

                if (allData.isEmpty()) {
                    return Mono.just(new DataAnalysisResultResponse());
                }

                // 4. 进行CT各通道的有效性判断
                List<DataAnalysisResultResponse.ChannelStat> channelStats = analyzeChannelValidity(allData);

                // 5. 查询阴阳判读条件配置
                return dataAnalysisInterpretationConditionService.listByGroupId(groupId)
                    .flatMap(conditions -> {
                        // 6. 根据阴阳判读条件配置进行阴阳判断
                        Map<String, Integer> interpretationResults = performInterpretation(allData, conditions);

                        // 统计结果
                        int positiveCount = 0, negativeCount = 0, invalidCount = 0;
                        for (Integer result : interpretationResults.values()) {
                            if (result == 1) {
                                positiveCount++;
                            } else if (result == 0) {
                                negativeCount++;
                            } else {
                                invalidCount++;
                            }
                        }

                        // 构建响应
                        DataAnalysisResultResponse response = new DataAnalysisResultResponse();
                        response.setTotalCount(allData.size());
                        response.setChannelStats(channelStats);
                        response.setPositiveCount(positiveCount);
                        response.setNegativeCount(negativeCount);
                        response.setInvalidCount(invalidCount);

                        return Mono.just(response);
                    });
            });
    }

    public Mono<Void> export(DataAnalysisRequest dataAnalysisRequest, ServerHttpResponse response) {

        DataBufferFactory bufferFactory = new DefaultDataBufferFactory();

        return dataAnalysisExperimentalRecordsService.listAllSelected(dataAnalysisRequest.getGroupId(), dataAnalysisRequest.getGroupTypeIds())
            .flatMap(dataList -> {

                if (dataList == null || dataList.isEmpty()) {
                    return Mono.error(new RuntimeException("没有找到要导出的数据"));
                }

                // 根据deviceName、moduleCode、name进行分组
                Map<String, List<DataAnalysisExperimentalRecordsEntity>> groupedData = dataList.stream()
                    .collect(Collectors.groupingBy(data ->
                        data.getDeviceName() + "_" + data.getModuleCode() + "_" + data.getName()
                    ));


                // 打印分组信息
                groupedData.forEach((key, group) -> {
                    System.out.println("分组: " + key + ", 数据条数: " + group.size());
                    if (!group.isEmpty()) {
                        DataAnalysisExperimentalRecordsEntity first = group.get(0);
                        System.out.println("  示例数据 - deviceName: " + first.getDeviceName() +
                            ", moduleCode: " + first.getModuleCode() +
                            ", name: " + first.getName() +
                            ", vic: " + first.getVic() +
                            ", cy5: " + first.getCy5() +
                            ", fam: " + first.getFam() +
                            ", rox: " + first.getRox());
                    }
                });

                // 处理分组后的数据，合并CT值并计算统计值
                List<ExportDataRow> exportRows = new ArrayList<>();
                for (List<DataAnalysisExperimentalRecordsEntity> groupData : groupedData.values()) {
                    List<ExportDataRow> rows = processGroupData(groupData);
                    if (rows != null) {
                        exportRows.addAll(rows);
                    }
                }

                // 按照整机编号 > 项目名称 > 模块编号的优先级进行排序
                exportRows.sort((row1, row2) -> {
                    // 首先按整机编号排序
                    int deviceNameCompare = compareStrings(row1.getDeviceName(), row2.getDeviceName());
                    if (deviceNameCompare != 0) {
                        return deviceNameCompare;
                    }

                    // 整机编号相同时，按项目名称排序
                    int nameCompare = compareStrings(row1.getName(), row2.getName());
                    if (nameCompare != 0) {
                        return nameCompare;
                    }

                    // 项目名称相同时，按模块编号排序
                    return compareStrings(row1.getModuleCode(), row2.getModuleCode());
                });


                if (exportRows.isEmpty()) {
                    return Mono.error(new RuntimeException("没有有效的数据可以导出"));
                }

                // 设置响应头
                try {
//                    获取当前系统时间格式yyyy-MM-dd HH:mm:ss
                    String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日HH时mm分ss秒"));
                    String fileName = URLEncoder.encode("数据分析导出-"+dataAnalysisRequest.getGroupId()+"-"+currentTime+".xlsx", StandardCharsets.UTF_8.displayName());
                    response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
                    response.getHeaders().set(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                } catch (Exception e) {
                    System.out.println("设置响应头失败: " + e.getMessage());
                }

                // 生成Excel数据流
                return ReactorExcel
                    .xlsxWriter()
                    .multiSheet()
                    .sheet(sheet -> {
                        sheet.headers(Arrays.asList(
                            new ExcelHeader("deviceName", "整机编号", CellDataType.STRING),
                            new ExcelHeader("moduleCode", "模块编号", CellDataType.STRING),
                            new ExcelHeader("name", "项目名称", CellDataType.STRING),
                            new ExcelHeader("channel", "荧光通道", CellDataType.STRING),
                            new ExcelHeader("ctValues", "Ct值", CellDataType.STRING),
                            new ExcelHeader("mean", "均值", CellDataType.NUMBER),
                            new ExcelHeader("sd", "SD", CellDataType.NUMBER),
                            new ExcelHeader("cv", "CV", CellDataType.STRING)
                        ));
                        sheet.rows(Flux.fromIterable(exportRows)
                            .map(row -> {
                                Map<String, Object> map = new HashMap<>();
                                map.put("deviceName", row.getDeviceName());
                                map.put("moduleCode", row.getModuleCode());
                                map.put("name", row.getName());
                                map.put("channel", row.getChannel());
                                map.put("ctValues", row.getCtValues());
                                map.put("mean", row.getMean());
                                map.put("sd", row.getSd());
                                // CV值格式化为两位小数并添加百分号
                                String cvFormatted = String.format("%.2f%%", row.getCv());
                                map.put("cv", cvFormatted);
                                return map;
                            }));
                    })
                    .writeBytes(1024 * 1024)
                    .map(bufferFactory::wrap)
                    .as(response::writeWith)
                    .doOnError(err -> System.out.println("导出失败: " + err.getMessage()));
            });
    }

    /**
     * 处理分组数据，合并CT值并计算统计值
     */
    private List<ExportDataRow> processGroupData(List<DataAnalysisExperimentalRecordsEntity> groupData) {
        if (groupData.isEmpty()) {
            return null;
        }

        DataAnalysisExperimentalRecordsEntity firstData = groupData.get(0);
        String deviceName = firstData.getDeviceName();
        String moduleCode = firstData.getModuleCode();
        String name = firstData.getName();


        // 收集所有有效的CT值
        List<Double> vicValues = new ArrayList<>();
        List<Double> cy5Values = new ArrayList<>();
        List<Double> famValues = new ArrayList<>();
        List<Double> roxValues = new ArrayList<>();

        for (DataAnalysisExperimentalRecordsEntity data : groupData) {
            // 只收集非空且大于0的CT值
            if (data.getVic() != null && data.getVic() > 0) {
                vicValues.add(data.getVic());
            }
            if (data.getCy5() != null && data.getCy5() > 0) {
                cy5Values.add(data.getCy5());
            }
            if (data.getFam() != null && data.getFam() > 0) {
                famValues.add(data.getFam());
            }
            if (data.getRox() != null && data.getRox() > 0) {
                roxValues.add(data.getRox());
            }
        }


        // 创建导出行数据
        List<ExportDataRow> rows = new ArrayList<>();

        // VIC通道
        if (!vicValues.isEmpty()) {
            rows.add(createExportRow(deviceName, moduleCode, name, "VIC", vicValues));
        }

        // Cy5通道
        if (!cy5Values.isEmpty()) {
            rows.add(createExportRow(deviceName, moduleCode, name, "Cy5", cy5Values));
        }

        // FAM通道
        if (!famValues.isEmpty()) {
            rows.add(createExportRow(deviceName, moduleCode, name, "FAM", famValues));
        }

        // ROX通道
        if (!roxValues.isEmpty()) {
            rows.add(createExportRow(deviceName, moduleCode, name, "ROX", roxValues));
        }


        return rows;
    }

    /**
     * 创建导出行数据
     */
    private ExportDataRow createExportRow(String deviceName, String moduleCode, String name,
                                        String channel, List<Double> values) {
        ExportDataRow row = new ExportDataRow();
        row.setDeviceName(deviceName);
        row.setModuleCode(moduleCode);
        row.setName(name);
        row.setChannel(channel);

        // 格式化CT值字符串
        String ctValuesStr = values.stream()
            .map(String::valueOf)
            .collect(Collectors.joining(","));
        row.setCtValues(ctValuesStr);

        // 计算统计值
        DescriptiveStatistics stats = new DescriptiveStatistics();
        values.forEach(stats::addValue);

        double mean = stats.getMean();
        double sd = stats.getStandardDeviation();
        double cv = mean > 0 ? (sd / mean) * 100 : 0; // CV = SD/均值 * 100%

        row.setMean(mean);
        // SD保留三位小数
        row.setSd(Math.round(sd * 1000.0) / 1000.0);
        row.setCv(cv);

        return row;
    }

    /**
     * 安全比较字符串，处理null值
     */
    private int compareStrings(String str1, String str2) {
        if (str1 == null && str2 == null) {
            return 0;
        }
        if (str1 == null) {
            return -1;
        }
        if (str2 == null) {
            return 1;
        }
        return str1.compareTo(str2);
    }

    /**
     * 测试导出功能
     */
    public Mono<String> testExport(DataAnalysisRequest dataAnalysisRequest) {
        return dataAnalysisExperimentalRecordsService.listAllSelected(dataAnalysisRequest.getGroupId(), dataAnalysisRequest.getGroupTypeIds())
            .map(dataList -> {
                if (dataList == null || dataList.isEmpty()) {
                    return "没有找到数据";
                }

                StringBuilder result = new StringBuilder();
                result.append("找到 ").append(dataList.size()).append(" 条数据\n");

                // 检查前几条数据的CT值
                for (int i = 0; i < Math.min(5, dataList.size()); i++) {
                    DataAnalysisExperimentalRecordsEntity data = dataList.get(i);
                    result.append("数据 ").append(i + 1).append(": ")
                          .append("deviceName=").append(data.getDeviceName())
                          .append(", moduleCode=").append(data.getModuleCode())
                          .append(", name=").append(data.getName())
                          .append(", vic=").append(data.getVic())
                          .append(", cy5=").append(data.getCy5())
                          .append(", fam=").append(data.getFam())
                          .append(", rox=").append(data.getRox())
                          .append("\n");
                }

                return result.toString();
            });
    }

    /**
     * 导出数据行类
     */
    public static class ExportDataRow {
        private String deviceName;
        private String moduleCode;
        private String name;
        private String channel;
        private String ctValues;
        private double mean;
        private double sd;
        private double cv;

        // Getters and Setters
        public String getDeviceName() { return deviceName; }
        public void setDeviceName(String deviceName) { this.deviceName = deviceName; }

        public String getModuleCode() { return moduleCode; }
        public void setModuleCode(String moduleCode) { this.moduleCode = moduleCode; }

        public String getName() { return name; }
        public void setName(String name) { this.name = name; }

        public String getChannel() { return channel; }
        public void setChannel(String channel) { this.channel = channel; }

        public String getCtValues() { return ctValues; }
        public void setCtValues(String ctValues) { this.ctValues = ctValues; }

        public double getMean() { return mean; }
        public void setMean(double mean) { this.mean = mean; }

        public double getSd() { return sd; }
        public void setSd(double sd) { this.sd = sd; }

        public double getCv() { return cv; }
        public void setCv(double cv) { this.cv = cv; }
    }


    /*******************************************************************************************************************/
    /*******************************************************Private方法**************************************************/
    /*******************************************************************************************************************/



    /**
     * 分析通道有效性
     * 判断规则：通道值不为空、并且大于0为有效
     */
    private List<DataAnalysisResultResponse.ChannelStat> analyzeChannelValidity(List<DataAnalysisExperimentalRecordsEntity> dataList) {
        List<DataAnalysisResultResponse.ChannelStat> channelStats = new ArrayList<>();

        // 用LinkedHashMap保证遍历顺序
        Map<String, java.util.function.Function<DataAnalysisExperimentalRecordsEntity, Double>> channelGetterMap = new LinkedHashMap<>();
        channelGetterMap.put("VIC", DataAnalysisExperimentalRecordsEntity::getVic);
        channelGetterMap.put("Cy5", DataAnalysisExperimentalRecordsEntity::getCy5);
        channelGetterMap.put("FAM", DataAnalysisExperimentalRecordsEntity::getFam);
        channelGetterMap.put("ROX", DataAnalysisExperimentalRecordsEntity::getRox);

        // 直接遍历map的key
        for (String channelName : channelGetterMap.keySet()) {
            java.util.function.Function<DataAnalysisExperimentalRecordsEntity, Double> getter = channelGetterMap.get(channelName);

            List<Double> validValues = dataList.stream()
                .map(getter)
                .filter(value -> value != null && value > 0)
                .collect(Collectors.toList());

            DataAnalysisResultResponse.ChannelStat stat = new DataAnalysisResultResponse.ChannelStat();
            stat.setChannelName(channelName);
            stat.setValidCount(validValues.size());

            if (!validValues.isEmpty()) {
                DescriptiveStatistics stats = new DescriptiveStatistics();
                validValues.forEach(stats::addValue);
                stat.setCtMean(stats.getMean());
                stat.setCtStd(stats.getStandardDeviation());
            } else {
                stat.setCtMean(0.0);
                stat.setCtStd(0.0);
            }

            channelStats.add(stat);
        }

        return channelStats;
    }

    /**
     * 根据阴阳判读条件配置进行阴阳判断
     */
    private Map<String, Integer> performInterpretation(List<DataAnalysisExperimentalRecordsEntity> dataList,
                                                      List<DataAnalysisInterpretationConditionEntity> conditions) {
        Map<String, Integer> results = new HashMap<>();

        for (DataAnalysisExperimentalRecordsEntity data : dataList) {
            String dataId = data.getId();

            // 按条件类型分组（阴性、阳性）
            Map<String, List<DataAnalysisInterpretationConditionEntity>> conditionsByType = conditions.stream()
                .collect(Collectors.groupingBy(DataAnalysisInterpretationConditionEntity::getConditionType));

            // 判断是否为阳性
            boolean isPositive = evaluateConditions(data, conditionsByType.get("POSITIVE"));
            // 判断是否为阴性
            boolean isNegative = evaluateConditions(data, conditionsByType.get("NEGATIVE"));

            // 确定结果：1=阳性，0=阴性，-1=无效
            int result;
            if (isPositive && !isNegative) {
                result = 1; // 阳性
            } else if (isNegative && !isPositive) {
                result = 0; // 阴性
            } else {
                result = -1; // 无效
            }

            results.put(dataId, result);
        }

        return results;
    }




    /**
     * 评估单个数据是否满足指定条件
     */
    private boolean evaluateConditions(DataAnalysisExperimentalRecordsEntity data,
                                       List<DataAnalysisInterpretationConditionEntity> conditions) {
        if (conditions == null || conditions.isEmpty()) {
            return false;
        }
        // 取数和判断是否满足条件
        if (conditions.size() > 1) {
            DataAnalysisInterpretationConditionEntity secondCondition = conditions.stream().filter(c -> c.getSort() > 1).findFirst().get();
            if (secondCondition.getConnector().equals("AND")) {
                return compareSingleCondition(data, conditions.get(0)) && compareSingleCondition(data, conditions.get(1));
            } else if (secondCondition.getConnector().equals("OR")) {
                return compareSingleCondition(data, conditions.get(0)) || compareSingleCondition(data, conditions.get(1));
            }
        } else {
            return compareSingleCondition(data, conditions.get(0));
        }
        return true;
    }

    /**
     * 比较单个条件是否满足
     */
    private boolean compareSingleCondition(DataAnalysisExperimentalRecordsEntity data, DataAnalysisInterpretationConditionEntity condition) {
        // 用LinkedHashMap保证遍历顺序
        Map<String, java.util.function.Function<DataAnalysisExperimentalRecordsEntity, Double>> channelGetterMap = new LinkedHashMap<>();
        channelGetterMap.put("CT_VIC", DataAnalysisExperimentalRecordsEntity::getVic);
        channelGetterMap.put("CT_Cy5", DataAnalysisExperimentalRecordsEntity::getCy5);
        channelGetterMap.put("CT_FAM", DataAnalysisExperimentalRecordsEntity::getFam);
        channelGetterMap.put("CT_ROX", DataAnalysisExperimentalRecordsEntity::getRox);
        channelGetterMap.put("AC", DataAnalysisExperimentalRecordsEntity::getAc);

        Map<String, java.util.function.Function<DataAnalysisExperimentalRecordsEntity, String>> tmChannelGetterMap = new LinkedHashMap<>();
        tmChannelGetterMap.put("TM_VIC", DataAnalysisExperimentalRecordsEntity::getTmVic);
        tmChannelGetterMap.put("TM_Cy5", DataAnalysisExperimentalRecordsEntity::getTmCy5);
        tmChannelGetterMap.put("TM_FAM", DataAnalysisExperimentalRecordsEntity::getTmFam);
        tmChannelGetterMap.put("TM_ROX", DataAnalysisExperimentalRecordsEntity::getTmRox);

        if (condition.getType().equals("CT")) {
            String channelName = condition.getType() + "_" + condition.getSubType();
            Function<DataAnalysisExperimentalRecordsEntity, Double> getter = channelGetterMap.get(channelName);
            Double value = getter.apply(data);
            if (value == null) {
                return false;
            }
            if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.GREATER_THAN) {
                return value > condition.getValue1();
            } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.LESS_THAN) {
                return value < condition.getValue1();
            } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.GREATER_THAN_OR_EQUAL) {
                return value >= condition.getValue1();
            } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.LESS_THAN_OR_EQUAL) {
                return value <= condition.getValue1();
            } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.EQUAL) {
                return Math.abs(value - condition.getValue1()) < 0.001;
            } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.NOT_EQUAL) {
                return Math.abs(value - condition.getValue1()) >= 0.001;
            } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.BETWEEN) {
                return value >= condition.getValue1() && value <= condition.getValue2();
            } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.NOT_BETWEEN) {
                return value < condition.getValue1() || value > condition.getValue2();
            }
        } else if (condition.getType().equals("AC")) {
            String channelName = condition.getType();
            Function<DataAnalysisExperimentalRecordsEntity, Double> getter = channelGetterMap.get(channelName);
            Double value = getter.apply(data);
            return Math.abs(value - condition.getValue1()) < 0.001;
        } else {
            String channelName = condition.getType() + "_" + condition.getSubType();
            Function<DataAnalysisExperimentalRecordsEntity, String> getter = tmChannelGetterMap.get(channelName);
            String value = getter.apply(data);
            if (StringUtils.isNotBlank(value)) {
                //转换为List<Double>
                List<Double> values = JSON.parseArray(value, Double.class);
                if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.GREATER_THAN) {
                    return values.stream().anyMatch(v -> v > condition.getValue1());
                } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.LESS_THAN) {
                    return values.stream().anyMatch(v -> v < condition.getValue1());
                } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.GREATER_THAN_OR_EQUAL) {
                    return values.stream().anyMatch(v -> v >= condition.getValue1());
                } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.LESS_THAN_OR_EQUAL) {
                    return values.stream().anyMatch(v -> v <= condition.getValue1());
                } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.EQUAL) {
                    return values.stream().anyMatch(v -> Math.abs(v - condition.getValue1()) < 0.001);
                } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.NOT_EQUAL) {
                    return values.stream().anyMatch(v -> Math.abs(v - condition.getValue1()) >= 0.001);
                } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.BETWEEN) {
                    return values.stream().anyMatch(v -> v >= condition.getValue1() && v <= condition.getValue2());
                } else if (InterpretationOperator.fromName(condition.getOperator()) == InterpretationOperator.NOT_BETWEEN) {
                    return values.stream().anyMatch(v -> v < condition.getValue1() || v > condition.getValue2());
                }
            }
            return false;
        }
        return false;
    }


}
